//
//  TimerManager.m
//  BlackGold
//
//  Created by Beyondream on 2017/10/12.
//  Copyright © 2017年 Beyondream. All rights reserved.
//

#import "TimerManager.h"

static TimerManager * manager = nil;

typedef void(^timeBlock)(NSString *currentString);

@interface TimerManager ()

@property (nonatomic,copy) timeBlock timeBlock;

@end

@implementation TimerManager {
    long _count;
    NSTimer * _timer;
}

+ (instancetype)shareManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[TimerManager alloc]init];
    });
    return manager;
}
- (void)startBtnClick:(void(^)(NSString *currentString))block{  //开始</span>
    self.timeBlock = block;
    [self invalidateTimer];
    _count = 0;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(repeatShowTime:) userInfo:@"admin" repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)stopBtnClick{  //停止</span>
    [self invalidateTimer];
    _count = 0;

}

- (void)pauseBtnClick{   //暂停</span>
    [_timer setFireDate:[NSDate distantFuture]];
}

- (void)continueClick{   //继续</span>
    [_timer setFireDate:[NSDate date]];
}


- (void)repeatShowTime:(NSTimer *)tempTimer {
    _count++;
    if (self.timeBlock) {
        self.timeBlock([self totalTime]);
    }
}

- (void)dealloc {   //销毁NSTimer</span>
    [self invalidateTimer];
}

- (void)invalidateTimer {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

- (NSString *)totalTime {
    //format of hour
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",_count/3600];
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(_count%3600)/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld",_count%60];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
    return format_time;
}
@end
